package com.edu.boot.config;

import com.edu.boot.entity.Users;
import org.springframework.stereotype.Component;

import java.util.Optional;
@Component
public class UserContext {
    private static final ThreadLocal<Users> USER_HOLDER = new ThreadLocal<>();
    
    public static void setUser(Users user) {
        USER_HOLDER.set(user);
    }
    
    public static Users getUser() {
        return USER_HOLDER.get();
    }
    
    public static Integer getUserId() {
        Integer uid = Optional.ofNullable(USER_HOLDER.get())
                .map(Users::getUid)
                .orElseThrow(() -> new RuntimeException("用户id获取失败"));
        return uid;
    }
    public static Integer getPid() {
        Integer pid = Optional.ofNullable(USER_HOLDER.get())
                .map(Users::getPid)
                .orElseThrow(() -> new RuntimeException("用户角色获取失败"));
        return pid;
    }
    public static void clear() {
        USER_HOLDER.remove();
    }
}
